#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "../ddxc.h"

// typedef struct msg{
//     char buf[CLIENT_BUF_SIZE];
//     int offset;
//     int blocksize;
//     long filesize;
//     char type;
// }msg,*msglist;

int get_file(int sockfd,const char* filename){
    msg node;
    int nodesize=sizeof(node);
    memset(&node,0,nodesize);

    if(msg1_file(sockfd,&node,filename,nodesize) == -1){
        close(sockfd);
        return -1;
    }

    if(msg3_block(sockfd,&node,filename) == -1){
        close(sockfd);
        return -1;
    }
    return 0;
}

int main(int argc, char const *argv[])
{
    //创建socket
    int sockfd;
     const char *message = "hello world";

    //./server <ip> <port> <file>
    if(argc < 4)
    {
        printf("usage: %s <ip> <port> <file>\n", argv[0]);
        return -1;
    }

    //创建一个socket文件描述符
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        perror("sock err");
        return -1;
    }

    //指定连接的服务器的地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));  //端口号
    addr.sin_addr.s_addr = inet_addr(argv[1]);  //IP



    int addrlen = sizeof(addr);
    if(connect(sockfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("connect err");
        return -1;
    }

    printf("connect success\n");


    //buf length
    // int ret = send(sockfd, message, strlen(message), 0);
    int ret = get_file(sockfd,argv[3]);


    if(ret < 0)
    {
        perror("send err");
        return -1;
    }

 

    close(sockfd);

    return 0;
}
